import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { authAPI } from '../api'
import { loginAPI } from '../api/login'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(null)
  const userRole = ref('') // 'admin', 'student', 'teacher'
  const isLoading = ref(false)

  // 计算属性
  const isAuthenticated = computed(() => !!token.value)
  const isAdmin = computed(() => userRole.value === 'admin')
  const isStudent = computed(() => userRole.value === 'student')
  const isTeacher = computed(() => userRole.value === 'teacher')

  // 管理员登录
  const adminLogin = async (credentials) => {
    try {
      isLoading.value = true
      const response = await authAPI.adminLogin(credentials)
      
      // 适配新的响应格式
      if (response.data && response.data.code === 200) {
        const data = response.data.data
        token.value = data.token
        userInfo.value = data.userInfo || data
        userRole.value = 'admin'
        
        localStorage.setItem('token', data.token)
        localStorage.setItem('userRole', 'admin')
        
        return { success: true }
      } else {
        return { success: false, message: response.data?.message || '登录失败' }
      }
    } catch (error) {
      return { success: false, message: error.response?.data?.message || error.message || '登录失败' }
    } finally {
      isLoading.value = false
    }
  }

  // 学生登录
  const studentLogin = async (credentials) => {
    try {
      isLoading.value = true
      const response = await authAPI.studentLogin(credentials)
      
      // 适配新的响应格式
      if (response.data && response.data.code === 200) {
        const data = response.data.data
        token.value = data.token
        userInfo.value = data.userInfo || data
        userRole.value = 'student'
        
        localStorage.setItem('token', data.token)
        localStorage.setItem('userRole', 'student')
        
        return { success: true }
      } else {
        return { success: false, message: response.data?.message || '登录失败' }
      }
    } catch (error) {
      return { success: false, message: error.response?.data?.message || error.message || '登录失败' }
    } finally {
      isLoading.value = false
    }
  }

  // 统一登录方法
  const login = async (credentials) => {
    try {
      isLoading.value = true
      const response = await loginAPI(credentials)
      
      console.log('🔍 API响应:', response)
      
      // 适配后端响应格式 - 后端成功返回code为1
      if (response && response.code === 1) {
        const data = response.data
        token.value = data.token
        userInfo.value = data
        
        // 根据role设置用户角色
        if (credentials.role === 0) {
          userRole.value = 'admin'
        } else if (credentials.role === 1) {
          userRole.value = 'student'
        }
        
        localStorage.setItem('token', data.token)
        localStorage.setItem('userRole', userRole.value)
        
        return response
      } else {
        return response
      }
    } catch (error) {
      console.error('登录API调用失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const response = await authAPI.getUserInfo()
      userInfo.value = response.userInfo
      userRole.value = response.role
      return response
    } catch (error) {
      console.error('获取用户信息失败:', error)
      logout()
    }
  }

  // 修改密码
  const changePassword = async (data) => {
    try {
      await authAPI.changePassword(data)
      return { success: true, message: '密码修改成功' }
    } catch (error) {
      return { success: false, message: error.message || '密码修改失败' }
    }
  }

  // 登出
  const logout = async () => {
    try {
      await authAPI.logout()
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      // 清除本地状态
      token.value = ''
      userInfo.value = null
      userRole.value = ''
      localStorage.removeItem('token')
      localStorage.removeItem('userRole')
    }
  }

  // 初始化用户状态
  const initAuth = () => {
    const savedToken = localStorage.getItem('token')
    const savedRole = localStorage.getItem('userRole')
    
    if (savedToken && savedRole) {
      token.value = savedToken
      userRole.value = savedRole
      // 获取用户信息
      getUserInfo()
    }
  }

  return {
    // 状态
    token,
    userInfo,
    userRole,
    isLoading,
    
    // 计算属性
    isAuthenticated,
    isAdmin,
    isStudent,
    isTeacher,
    
    // 方法
    login,
    adminLogin,
    studentLogin,
    getUserInfo,
    changePassword,
    logout,
    initAuth
  }
})